<template>
	<view>		
		<!-- 假的留言框，仅仅是用来触发弹窗 -->
		<view class="dflex wrap mt12">
			<view class="article_comments_avatar">
				<image :src="loginAvatarSrc" class="mr10" mode="scaleToFill" v-if="loginCheck" @click="toFatherMemberIndex" :data-currentuid="loginUserId"></image>
				<image :src="defaultAvatarSrc" class="mr10" mode="scaleToFill" v-else></image>
			</view>
			<view class="article_comments_input fg1" @click="openSendMessage">
				<u--input
					border="surround"
					placeholder="听说爱评论的人粉丝多哟..."
					disabled="true"
					disabledColor="#ffffff"
					shape="circle"
					type="text"
					prefixIcon="chat"
				></u--input>
			</view>
		</view>
		
		<!-- 正常回复 -->
		<view class="pop_message_box">
			<u-popup :show="showSendMessagePopBox" @close="close">
				<view class="article_pop_comments_input fg1 wrap_nb">
					<u-scroll-list :indicator="indicator">
						 <view class="reply_ico dflex">
							<text data-emoji="😀" @click="addEmojiToReply">😀</text>
							<text data-emoji="😁" @click="addEmojiToReply">😁</text>
							<text data-emoji="😂" @click="addEmojiToReply">😂</text>
							<text data-emoji="😃" @click="addEmojiToReply">😃</text>
							<text data-emoji="😄" @click="addEmojiToReply">😄</text>
							<text data-emoji="🌜" @click="addEmojiToReply">🌜</text>
							<text data-emoji="🌞" @click="addEmojiToReply">🌞</text>
							<text data-emoji="🎉" @click="addEmojiToReply">🎉</text>
							<text data-emoji="🍭" @click="addEmojiToReply">🍭</text>
							<text data-emoji="🎀" @click="addEmojiToReply">🎀</text>
							<text data-emoji="🎈" @click="addEmojiToReply">🎈</text>
							<text data-emoji="🎌" @click="addEmojiToReply">🎌</text>
							<text data-emoji="🌈" @click="addEmojiToReply">🌈</text>
							<text data-emoji="💔" @click="addEmojiToReply">💔</text>
							<text data-emoji="💕" @click="addEmojiToReply">💕</text>
						</view>					
					</u-scroll-list>
					<view class="dflex aic" style="margin-bottom: 20px;">
						<view class="fg1">
							<u--form
								labelPosition="left"
								:model="userModel"
								ref="userReplyForm"
							>	
								<u-form-item
										prop="user.replyContent"
										ref="item1"
								>
									<input
										v-model="userModel.user.replyContent"
										border="surround"
										placeholder="听说爱评论的人粉丝多哟..."
										confirmType="send"
										prefixIcon="chat"
										shape="circle"
										type="text"
										ref="popInput"
										:auto-blur="true"
										@blur="blurReply"
										@confirm="sendReplyMessage"
									></input>
								</u-form-item>
							</u--form>
						</view>
						<view class="f12 ml5 small_follow_button dflex" @click="sendReplyMessage">
							发布
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		
		<!-- 回复特定人 -->
		<view class="pop_message_box">
			<u-popup :show="showSendMessageToSomebody" @close="closeToSomeBody">
				<view class="article_comments_input fg1 wrap">
					<u-scroll-list :indicator="indicator">
						 <view class="reply_ico dflex">
							<text data-emoji="😀" @click="addEmojiToSecreply">😀</text>
							<text data-emoji="😁" @click="addEmojiToSecreply">😁</text>
							<text data-emoji="😂" @click="addEmojiToSecreply">😂</text>
							<text data-emoji="😃" @click="addEmojiToSecreply">😃</text>
							<text data-emoji="😄" @click="addEmojiToSecreply">😄</text>
							<text data-emoji="🌜" @click="addEmojiToSecreply">🌜</text>
							<text data-emoji="🌞" @click="addEmojiToSecreply">🌞</text>
							<text data-emoji="🎉" @click="addEmojiToSecreply">🎉</text>
							<text data-emoji="🍭" @click="addEmojiToSecreply">🍭</text>
							<text data-emoji="🎀" @click="addEmojiToSecreply">🎀</text>
							<text data-emoji="🎈" @click="addEmojiToSecreply">🎈</text>
							<text data-emoji="🎌" @click="addEmojiToSecreply">🎌</text>
							<text data-emoji="🌈" @click="addEmojiToSecreply">🌈</text>
							<text data-emoji="💔" @click="addEmojiToSecreply">💔</text>
							<text data-emoji="💕" @click="addEmojiToSecreply">💕</text>
						</view>					
					</u-scroll-list>
					<view class="dflex aic">
						<view class="fg1">
							<u--form
								labelPosition="left"
								:model="userSecModel"
								:rules="rules"
								ref="userSecreplyForm"
							>	
								<u-form-item 
									prop="user.secreplyContent"
									ref="item1"
									>							
									<u-input								
										v-model="userSecModel.user.secreplyContent"
										border="surround"
										placeholder="对他说点啥"
										confirmType="send"
										shape="circle"
										type="text"
										ref="popInput"
										:focus="popSomebodyFocus"
										@confirm="sendSecreplyMessage"
									>
											<u--text
												:text="replyUserName"
												slot="prefix"
												margin="0 3px 0 0"
												type="tips"
											></u--text>
									</u-input>
								</u-form-item>
							</u--form>	
						</view>				
						<view class="f12 ml5 small_follow_button dflex" @click="sendSecreplyMessage">
							回复
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		
		<view class="empty_list mt12" v-if="empty">
			<u-empty mode="data" text="还没有留言"></u-empty>
		</view>
		
		<view class="wrap mt12" v-if="loading">
			<u-loadmore status="loading" />
		</view>
		
		<!-- 正常评论 -->
		<view class="reply_main_box" v-for="(item, index) in replyList" :key="index">
			<view class="wrap_nb article_comments_box dflex ait">			
				<view class="article_comments_box_avater mr12" @click="toFatherMemberIndex" :data-currentuid="item.user.id">
					<image :src="item.user.avatar" class="w30 mr10" mode="" :data-currentuid="item.user.id"></image>
				</view>
				<view class="cflex fg1">
					<view class="dflex">
						<view class="article_comments_box_text cflex mr12 fg1">
							<view class="dflex">
								<text class="f14 fbold mb7 ca3a3a3" @click="toFatherMemberIndex" :data-currentuid="item.user.id">{{ item.user.name }}</text>
								<view 
									class="ml5 main_color main_bg border-aroud cflex aic" 
									style="height: 15px; padding:2px 7px;"
									v-if="item.user_id == topicCurrentUserId"
								>
									<text class="f10">楼主</text>
								</view>
							</view>
							<text class="f14 mb7" 
								@click="replySomebody" 
								:data-masterName="item.user.name" 
								:data-replyid="item.id"
								:data-replyindex="index"
							>
								{{ item.content}}
							</text>
							<view class="dflex">
								<text class="f12 ca3a3a3 mr10">{{ item.created_at }}</text>
								<view class="dflex" 
									v-if="item.user.id == loginUserId" 
									:data-deletereplyid="item.id"									
									:data-deleteindex="index"
									@click="deleteReply"
								>
									<u-icon name="trash"></u-icon>
									<text class="f12 ca3a3a3">删除</text>
								</view>
							</view>
						</view>
						<view class="article_comments_box_zan dflex aic" ref="likeIcon">
							<image :src="'/static/' + item.zan + '.png'" class="w20 mr5" @click="replyLike" :data-clickreplyid="index" :data-replyid="item.id" :id="'reply' + (item.id)"></image>
							<text class="f12">{{ item.like_count }}</text>
						</view>
					</view>
					<view class="mt12">
						<u-line></u-line>
					</view>
				</view>
			</view>
			
			<!-- 回复的评论 -->
				<!-- 开启多页 -->
				<!-- v-if="(item.secreplies.data).length > 0" -->
				<!-- v-for="(secreply, index2) in item.secreplies.data" -->
			<view class="wrap_nb article_comments_box dflex ait comments_reply" 
					v-if="(item.secreplies).length > 0"
					v-for="(secreply, index2) in item.secreplies"
					:key="index2"
				>			
				<view class="article_comments_box_avater mr12" @click="toFatherMemberIndex" :data-currentuid="secreply.user.id">
					<image :src="secreply.user.avatar" class="w30 mr10" mode="" :data-currentuid="secReply.user.id"></image>
				</view>
				<view class="cflex fg1">
					<view class="dflex">
						<view class="article_comments_box_text cflex mr12 fg1">
							<view class="dflex">
								<text class="f14 fbold mb7 ca3a3a3" @click="toFatherMemberIndex" :data-currentuid="secreply.user.id">{{ secreply.user.name }}</text>
								<view 
									class="ml5 main_color main_bg border-aroud cflex aic" 
									style="height: 15px; padding:2px 7px;"
									v-if="secreply.user.id == topicCurrentUserId"
								>
									<text class="f10">楼主</text>
								</view>
							</view>
							<text class="f14 mb7" 
								@click="replySomebody" 
								:data-masterName="secreply.user.name" 
								:data-replyid="item.id"
								:data-replyindex="index"
							>
								{{ secreply.content }}
							</text>
							<view class="dflex">
								<text class="f12 ca3a3a3 mr10">{{  secreply.created_at }}</text>
								<view class="dflex" 					
									v-if="secreply.user.id == loginUserId"
									:data-deletereplyid="item.id"			
									:data-deletesecreplyid="secreply.id"								
									:data-deleteindex="index"									
									:data-deletesecindex="index2"
									@click="deleteSecreply"
								
								>
									<u-icon name="trash"></u-icon>
									<text class="f12 ca3a3a3">删除</text>
								</view>
							</view>
						</view>
						<view class="article_comments_box_zan dflex aic" ref="secreply_like_count">
							<image :src="'/static/' + secreply.zan + '.png'" class="w20 mr5" @click="replyLike" :data-clickreplyid="index" :data-clicksecreplyid="index2" :data-secreplyid="secreply.id"></image>
							<text class="f12">{{ secreply.like_count }}</text>
						</view>
					</view>
					<view class="mt12">
						<u-line></u-line>
					</view>
				</view>
			</view>
		</view>
		
		<u-toast ref="uToast"></u-toast>
		
	</view>
</template>

<script>
	
	
	export default {
		name:"reply",
		props: {
			defaultAvatarSrc : '',
			loginAvatarSrc : '',
			is_self : '',
			loginCheck : '',
			topicCurrentUserId : '',
			topicCurrentId : '',
			loginUserId : ''
		},
		onReady:function(){
			if(uni.getStorageSync("login_type")) {
				this.login_type = true
			}
			//获取用户未登录时发布的留言
			// console.log('123123123', uni.getStorageSync('secreplyMessageWithOutLogin'))	
			this.userSecModel.user.secreplyContent = uni.getStorageSync('secreplyMessageWithOutLogin')
			this.userModel.user.replyContent = uni.getStorageSync('replyMessageWithOutLogin')
		},
		data() {
			return {
				replyList : [],
				secReply : [],
				empty : false,
				loading : true,
				rules: {
					'user.replyContent': {
						type: 'string',
						max: 100,
						required: true,
						message: [],
						trigger: []
					},
				},
				userModel : {
					user : {
						replyContent : ''
					}
				},
				userSecModel : {
					user : {
						secreplyContent : ''
					}
				},
				showSendMessagePopBox : false,
				showSendMessageToSomebody : false,
				popSomebodyFocus : false,
				replyUserName : '',
				hasSecReply : false,
				replyindex : '',
				page : 1,
				total_page : 0,
				clickCurrentReply : '',
				clickCurrentSecreplyid : '',
				selectPos : 0
			};
		},
		methods : {
			addEmojiToReply(e) {
				// console.log(event)
				const emoji = e.currentTarget.dataset.emoji;
				const replyContent = this.userModel.user.replyContent;
				this.userModel.user.replyContent = replyContent.substring(0, this.selectPos)
					+ emoji 
					+ replyContent.substring(this.selectPos, replyContent.length);
				//光标后移两位
				this.selectPos += 3
			},
			blurReply(e){
                // this.popFocus = true; //保持焦点
                this.selectPos = e.target.cursor //保存光标位置
				console.log('blur1',e)
				console.log('blur2',this.selectPos)
            },
			addEmojiToSecreply(e) {
				// console.log(this.userModel.user.replyContent, e.currentTarget.dataset.emoji)
				this.userSecModel.user.secreplyContent = this.userSecModel.user.secreplyContent + e.currentTarget.dataset.emoji
				this.popSomebodyFocus = true;
			},
			show_toast(mes) {
				this.$refs.uToast.show({
					message : mes,
				})
			},
			toFatherMemberIndex(e){
				this.$emit('toMemberIndex', e);
			},
			formIndexReachBottom() {
				// console.log('aaaa',this.page)
				// console.log('cccc',this.total_page)
				// console.log('dddd',this.page <= this.total_page)
				if(this.page <= this.total_page) {
					this.getReplies()
				}
			},
			deleteReply(e) {
				uni.showLoading({
					title: '加载中...',
					mask: false
				})
				// console.log(this.replyList[e.currentTarget.dataset.deleteindex])
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/topics/' + this.topicCurrentId + '/replies/' + e.currentTarget.dataset.deletereplyid,
					method:'DELETE',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					success: (res) => {
						if(res.data.status == 'success') {
							this.show_toast('删除成功')
							this.replyList.splice(e.currentTarget.dataset.deleteindex, 1)
							if(this.replyList.length == 0) {
								this.empty = true
							}
							uni.hideLoading()
						}
					},
					fail: (res) => {
						console.log(res)
					}
				})	
			},
			deleteSecreply(e) {
				uni.showLoading({
					title: '加载中...',
					mask: false
				})
				uni.request({
					// api/v1/replies/{reply}/secreplies/{secreply}
					url:uni.getStorageSync('domain') + '/api/v1/replies/' + e.currentTarget.dataset.deletereplyid + '/secreplies/' + e.currentTarget.dataset.deletesecreplyid,
					method:'DELETE',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					success: (res) => {
						if(res.data.status == 'success') {
							this.show_toast('删除成功')
							this.replyList[e.currentTarget.dataset.deleteindex].secreplies.splice(e.currentTarget.dataset.deletesecindex, 1)
							uni.hideLoading()
						}
					},
					fail: (res) => {
						console.log(res)
					}
				})					
			},
			getReplies() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/topics/' + uni.getStorageSync('topic_id') + '/replies?&loginUser=' + this.loginUserId + '&include=user,secreplies&page=' + this.page,
					method:'GET',
					header: {
						'Accept': 'application/json',
					},
					success: (res) => {
						this.total_page = res.data.meta.last_page
						if(res.data.meta.total == 0) {
							this.total_page = 0
							this.empty = true
						} else {
							if(this.page == 1){							
								this.replyList = res.data.data
							}
							if(this.page > 1 & this.page <= this.total_page) {							
								this.replyList = [...this.replyList,...res.data.data]
							}
							if(this.page <= this.total_page) {
								this.page++
							}
							// console.log('replyList', this.replyList)
							// if(res.data.data.secreplies) {
							// 	this.hasSecReply = true
							// 	this.secReply = res.data.data.secreplies
							// }
							console.log(this.page, this.total_page)
						}
						this.loading = false;
						uni.hideLoading();
					},
					fail: (res) => {
						console.log('fail', res)
					}
				})	
			},
			openSendMessage() {
				this.showSendMessagePopBox = true;
				this.$nextTick(() => {					
					this.popFocus = true;
					// console.log(this.popFocus);
				})
				// console.log(this.$refs.popInput.focus );
			},
			replySomebody(e) {
				this.replyindex = e.currentTarget.dataset.replyindex
				console.log(this.replyindex);
				this.showSendMessageToSomebody = true;
				//获取要被回复信息的id
				this.secreplyCurrentId = e.currentTarget.dataset.replyid
				// console.log('111111111111111',this.secreplyCurrentId);
				//获取被回复者用户名
				this.replyUserName = '回复' + e.currentTarget.dataset.mastername + ':';
				this.$nextTick(() => {					
					this.popSomebodyFocus = true;
					// console.log(this.popSomebodyFocus);
				})
			},
			closeToSomeBody() {
				this.showSendMessageToSomebody = false;
				//重置留言框focus状态，否则只能在第一次聚焦
				this.popSomebodyFocus = false;
			},			
			sendReplyMessage() {
				if(this.loginCheck == true) {
					// console.log("发布留言：" + this.userModel.user.replyContent)
					uni.showLoading({
						title: '加载中...',
						mask: true
					});		
					//检测完成开始发布							
					uni.request({
						url:uni.getStorageSync('domain') + '/api/v1/topics/' + this.topicCurrentId + '/replies',
						method:'POST',
						header: {
							'Accept': 'application/json',
							'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
						},
						data: {
							'content' : this.userModel.user.replyContent,
						},
						success: (res) => {									
							if(res.data.status == 'repeat') {
								uni.showModal({
									title:'提示',
									content:'请勿回复重复内容！',
									showCancel:false
								})
								uni.hideLoading();
								return
							}						
							if(res.statusCode != 201) {
								uni.$u.toast(res.data.message)
							}
							// console.log('reply', res.data.user.avatar);
							if(res.statusCode == 201) {
								//清空留言发布框
								this.userModel.user.replyContent = ""
								//清空可能存在的用户未登录发布的内容
								uni.removeStorageSync('replyMessageWithOutLogin')
								this.replyList.unshift({
									'content' : res.data.replayData.content,
									'created_at' : res.data.replayData.created_at,
									'id' : res.data.replayData.id,
									'like_count' : 0,
									'zan' : 'zan',
									'topic_id' : res.data.replayData.topic.id,
									'user_id' : uni.getStorageSync('access_member_info').user_base.id,
									//如果不新建一个空数组，用户发布留言以后马上自己回复自己就会报错
									'secreplies' : new Array(),
									'user' : {
										'avatar' : uni.getStorageSync('access_member_info').user_base.avatar,
										'id' : uni.getStorageSync('access_member_info').user_base.id,
										'name' : uni.getStorageSync('access_member_info').user_base.name
									}
								})
								this.empty = false;
								this.$emit("getReplyCount", res.data.reply_count);
							}
							// console.log('replyList', this.replyList)
							uni.hideLoading();
							this.showSendMessagePopBox = false;
							// console.log(res);
							//重置留言框focus状态，否则只能在第一次聚焦
							this.popFocus = false;
						},
						fail: (res) => {
						}
					})	
					//检测完成开始发布
					//重置留言框focus状态，否则只能在第一次聚焦	
					this.popFocus = false;
				} else {
					uni.setStorageSync('replyMessageWithOutLogin', this.userModel.user.replyContent)
					this.$emit("gotoRegister")
				}
			},
			sendSecreplyMessage() {
				if(this.loginCheck == true) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				//检测完成开始发布
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/replies/' + this.secreplyCurrentId + '/secreplies',
					method:'POST',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					data: {
						'content' : this.userSecModel.user.secreplyContent,
					},
					success: (res) => {						
						if(res.data.status == 'repeat') {
							uni.showModal({
								title:'提示',
								content:'请勿回复重复内容！',
								showCancel:false
							})
							uni.hideLoading();
							return
						}
						if(res.statusCode != 201) {
							uni.$u.toast(res.data.message)
						}
						// console.log('111111111',this.replyList);
						// console.log('222222222',this.replyList[this.replyindex]);
						// console.log('333333333',this.replyList[this.replyindex].secreplies);
						if(res.statusCode == 201 || res.statusCode == 201) {	
							//清空输入框内已发布内容
							this.userSecModel.user.secreplyContent = ""
							//清空可能存在的用户未登录发布的内容
							uni.removeStorageSync('secreplyMessageWithOutLogin')					
							this.replyList[this.replyindex].secreplies.unshift({
								'content' : res.data.content,
								'created_at' : '刚刚',
								'updated_at' : '刚刚',
								'id' : res.data.id,
								'like_count' : 0,
								'reply_id' : res.data.reply_id,
								'topic_id' : res.data.topic_id,
								'zan' : 'zan',
								'user_id' : uni.getStorageSync('access_member_info').user_base.id,
								'user' : {
									'avatar' : uni.getStorageSync('access_member_info').user_base.avatar,
									'id' : uni.getStorageSync('access_member_info').user_base.id,
									'name' : uni.getStorageSync('access_member_info').user_base.name
								}
							})
							this.empty = false;
							this.reply_count = res.data.reply_count;
						}	
						uni.hideLoading();
						this.showSendMessageToSomebody = false;
						//重置留言框focus状态，否则只能在第一次聚焦
						this.popSomebodyFocus = false;
						// console.log(res);
					},
					fail: (res) => {
					}
				})
				//检测完成开始发布
				//重置留言框focus状态，否则只能在第一次聚焦	
				this.popFocus = false;
				} else {
					uni.setStorageSync('secreplyMessageWithOutLogin', this.userSecModel.user.secreplyContent)
					this.$emit("gotoRegister")
				}
			},
			close() {
				this.showSendMessagePopBox = false;
				//重置留言框focus状态，否则只能在第一次聚焦
				this.popFocus = false;
			},
			//评论点赞、取消、状态
			replyLike(e) {
				// console.log('11111111111111', e.currentTarget.dataset)
				// console.log('22222222222222', e)
				
				this.clickCurrentReply = e.currentTarget.dataset.clickreplyid;
				
				this.clickCurrentSecreply = e.currentTarget.dataset.clicksecreplyid;
				
				// console.log(e.target.getAttribute('src'));
				if(this.loginCheck == true) {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					uni.request({
						url:uni.getStorageSync('domain') + '/api/v1/users/reply_likes/' + this.topicCurrentId,
						method:'POST',
						header: {
							'Accept': 'application/json',
							'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
						},
						data: {
							'reply_id' : e.currentTarget.dataset.replyid,
							'secreply_id' : e.currentTarget.dataset.secreplyid
						},
						success: (res) => {
							// console.log('1111', res);					
							
							if(res.data.status == 'done') {
								//如果点击了评论，就有reply index，更新对应的数组
								if(this.clickCurrentReply >= 0 &&  this.clickCurrentSecreply == null) {
									this.replyList[this.clickCurrentReply].like_count = res.data.reply_like_count
									this.replyList[this.clickCurrentReply].zan = 'zan_h'				
								}
								//如果点击了评论的回复，就有reply index和secreply index2，更新对应的数组
								if(this.clickCurrentReply >= 0 && this.clickCurrentSecreply >= 0) {
									this.replyList[this.clickCurrentReply].secreplies[this.clickCurrentSecreply].like_count = res.data.secreply_like_count
									this.replyList[this.clickCurrentReply].secreplies[this.clickCurrentSecreply].zan = 'zan_h'
								}
							}
							
							if(res.data.status == 'delete') {
								//如果点击了评论，就有reply index，更新对应的数组
								if(this.clickCurrentReply >= 0 &&  this.clickCurrentSecreply == null) {
									this.replyList[this.clickCurrentReply].like_count = res.data.reply_like_count
									this.replyList[this.clickCurrentReply].zan = 'zan'				
								}
								//如果点击了评论的回复，就有reply index和secreply index2，更新对应的数组
								if(this.clickCurrentReply >= 0 && this.clickCurrentSecreply >= 0) {
									this.replyList[this.clickCurrentReply].secreplies[this.clickCurrentSecreply].like_count = res.data.secreply_like_count
									this.replyList[this.clickCurrentReply].secreplies[this.clickCurrentSecreply].zan = 'zan'
								}
							}
							
							uni.hideLoading()
						},
						fail: (res) => {
						}
					})
				} else {
					this.$emit("gotoRegister")
				}
			},
		}
	}
</script>

<style>

</style>